import * as THREE from '../../build/three.module.js'
import Stat from '../../jsm/libs/stats.module.js';

let widthHalf = innerWidth / 2;
let heightHalf = innerHeight / 2;
let mouseX = 0;
let mouseY = 0;

const scene = new THREE.Scene();
scene.background = new THREE.Color(0xffffff);

const group = new THREE.Group();

const slt = new THREE.BoxBufferGeometry(100, 100, 100);
const mtl = new THREE.MeshNormalMaterial();

for(let i =  0; i < 1000; i += 1) {
  let mesh = new THREE.Mesh(slt, mtl);

  mesh.position.x = Math.random() * 2000 - 1000;
  mesh.position.y = Math.random() * 2000 - 1000;
  mesh.position.z = Math.random() * 2000 - 1000;

  mesh.rotation.x = Math.random() * 2 * Math.PI;
  mesh.rotation.y = Math.random() * 2 * Math.PI;

  mesh.matrixAutoUpdate = false;
  mesh.updateMatrix();
  
  group.add(mesh);
}

scene.add(group);

const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 10000);
camera.position.set(0, 0, 500);

const acesH = new THREE.AxesHelper(1000);
scene.add(acesH);

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

const stats = new Stat();
document.body.appendChild(stats.dom);

const render = () => {
  const time = Date.now() * .001;

  const rx = Math.sin(time * .7) * .5,
        ry = Math.sin(time * .3) * .5,
        rz = Math.sin(time * .2) * .5;
  
  camera.position.x += (mouseX - camera.position.x) * .05;
  camera.position.y += (-mouseY - camera.position.y) * .05;

  camera.lookAt(scene.position);

  group.rotation.x = rx;
  group.rotation.y = ry;
  group.rotation.z = rz;

  renderer.render(scene, camera);
};

const animate = () => {
  requestAnimationFrame(animate);

  stats.update();
  render();
}
animate();

// 事件监听
const handleWindowResize = () => {
  widthHalf = innerWidth / 2;
  heightHalf = innerHeight / 2;

  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(innerWidth, innerHeight);
}
window.addEventListener('resize', handleWindowResize);

const handleMouseMove = (e) => {
  mouseX = (e.clientX - widthHalf) * 10;
  mouseY = (e.clientY - heightHalf) * 10;
}
document.addEventListener('mousemove', handleMouseMove);